package com.meida.module.arc.provider.handler;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.module.ExportField;
import com.meida.common.base.module.MyExportParams;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.interceptor.ExportInterceptor;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.utils.ApiAssert;
import com.meida.module.arc.client.entity.ArcCategory;
import com.meida.module.arc.client.entity.ArcField;
import com.meida.module.arc.provider.service.ArcCategoryService;
import com.meida.module.arc.provider.service.ArcDictService;
import com.meida.module.arc.provider.service.ArcFieldService;
import com.meida.module.arc.provider.service.ArcInfoService;
import com.meida.module.system.client.entity.SysDept;
import com.meida.module.system.provider.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <b>功能名：ArcInfoExportHandler</b><br>
 * <b>说明：</b><br>
 * <b>著作权：</b> Copyright (C) 2021 HUIFANEDU  CORPORATION<br>
 * <b>修改履历：
 *
 * @author 2022-02-11 jiabing
 */
@Service("arcInfoStoreExportHandler")
@Transactional(rollbackFor = Exception.class)
@DS("sharding")
public class ArcInfoStoreExportHandler implements ExportInterceptor {

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private ArcInfoService arcInfoService;

    @Autowired
    private ArcCategoryService arcCategoryService;


    @Override
    public void initExcelExportEntity(ExportField exportField, List list) {
        if (FlymeUtils.isEmpty(exportField)) {
            //根据门类查询 导出的字段列表
            ServletRequestAttributes servletRequestAttributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            Map param = (Map) request.getAttribute("reqParam");
            Object categoryId = param.get("categoryId");
            ApiAssert.isNotEmpty("门类id为空", categoryId);
            List<ArcField> fields = arcFieldService.listByCategoryId(Long.parseLong(categoryId.toString()));
            fields.stream().filter(field -> {
                return field.getOutIsShow() == 1;
            }).sorted(Comparator.comparing(ArcField::getOutSeq))
                    .forEach(item -> {
                        ExportField obj = new ExportField();
                        obj.setEntityName(item.getFieldCnName());
                        obj.setKey(item.getFieldName());
                        obj.setName(item.getFieldCnName());
                        obj.setStatistics(false);
                        if (FlymeUtils.isNotEmpty(item.getDictCode())) {
                            obj.setDict("arcDict");
                        }
                        if (item.getFieldName().equals("unitId")) {
                            obj.setDict("unitId");
                        }
                        if (item.getFieldName().equals("isCompilation")) {
                            obj.setKey("compilationName");
                        }
                        if (item.getFieldName().equals("isStore") || item.getFieldName().equals("storeRoomId")) {
                            obj.setKey("storeLocationName");
                        }
                        list.add(obj);
                    });
        }
    }

    @Autowired
    private ArcFieldService arcFieldService;

    @Autowired
    private ArcDictService arcDictService;


    @Override
    public void initExportParams(MyExportParams exportParams) {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Map param = (Map) request.getAttribute("reqParam");
        Object categoryId = param.get("categoryId");
        ApiAssert.isNotEmpty("门类id不能为空", categoryId);
        ArcCategory category = this.arcCategoryService.getById(Long.parseLong(categoryId.toString()));
        //初始化字典
        Map dictQueryMap = new HashMap();
        dictQueryMap.put("qzId", category.getQzId());
        ResultBody result = arcDictService.listEntityMap(dictQueryMap);
        List<EntityMap> dictList = (List) result.getData();
        Map<String, Map<String, Object>> dictMap = new HashMap<>();

        Map dbDict = dictList.stream().filter(item -> {
            return FlymeUtils.isNotEmpty(item.get("dictCode")) && FlymeUtils.isNotEmpty(item.get("dictName"));
        }).collect(Collectors.toMap(item -> {
            return item.get("dictCode").toString();
        }, item -> {
            return item.get("dictName").toString();
        }));
        dictMap.put("arcDict", dbDict);

        //初始化机构名称字典
        QueryWrapper<SysDept> query = new QueryWrapper();
        query.lambda().eq(SysDept::getCompanyId, category.getQzId());
        List<SysDept> deptList = this.sysDeptService.list(query);
        dictMap.put("unitId", deptList.stream().collect(Collectors.toMap(item -> {
            return item.getDeptId().toString();
        }, item -> {
            return item.getDeptName();
        })));
        exportParams.setDictHandler(new ExportDictHandler(dictMap));
    }


    @Override
    public ResultBody initData(Map params) {
        ResultBody resultBody = arcInfoService.listEntityMap(params);

        List<Map> list = (List<Map>) resultBody.getData();
        if (FlymeUtils.isEmpty(list)) {
            return ResultBody.failed("");
        }
        //((List<Map>) resultBody.getData()).stream().map(item -> Long.parseLong(item.get("arcInfoId").toString())).collect(Collectors.toList());
        Map<Long, Object> arcInfoIds = list.stream().collect(Collectors.toMap(item -> {
            return (Long) item.get("arcInfoId");
        }, item -> {
            Object value = item.get("arcNo");
            if (FlymeUtils.isEmpty(value)) {
                value = item.get("maintitle");//题名
            }
            if (FlymeUtils.isEmpty(value)) {
                value = item.get("arcInfoId");
            }
            return value;
        }));


        return resultBody;
    }


}
